<template>
  <div class="merchant-list">
    <el-card class="mb-4">
      <el-form :inline="true" :model="searchForm" class="demo-form-inline">
        <el-form-item label="员工">
          <el-select filterable  v-model="searchForm.employeeId" clearable placeholder="请选择员工">
            <el-option label="全部" value="" />
            <el-option :label="item.nickname" :value="item.id" v-for="item,index in merchantList" :key="index" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select filterable  v-model="searchForm.status" clearable placeholder="请选择状态">
            <el-option label="全部" value="" />
            <el-option label="启用" :value="1" />
            <el-option label="禁用" :value="0" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="resetSearch">重置</el-button>
          <el-button type="primary" @click="handleAdd" style="margin-left: 30px"
            v-has="'employeeCard:save'">新增员工卡</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  
    <!-- 表格 -->
    <el-table v-loading="loading" :data="tableData" border style="width: 100%;margin-top:15px">
      <el-table-column prop="id" label="ID" width="80" />
      <el-table-column prop="employeeNo" label="员工编号" />
      <el-table-column prop="employeeName" label="员工姓名" />
      <el-table-column prop="cardNo" label="卡号" width="100" />
      <el-table-column prop="status" label="状态" width="100">
        <template #default="{ row }">
          <el-tag :type="row.status === 1 ? 'success' : 'danger'">
            {{ row.status === 1 ? '启用' : '禁用' }}
          </el-tag>
        </template>
      </el-table-column>
      <!-- <el-table-column prop="floors" label="楼层列表" width="170" /> -->
      <el-table-column label="操作" width="120" fixed="right">
        <template #default="{ row }">
          <el-button type="text" v-has="'employeeCard:change'" @click="handleEdit(row)">换卡</el-button>
          <el-button type="text" style="color: #f56c6c" v-has="'employeeCard:status'"
            @click="handleDelete(row)">{{row.status == 1 ? '禁用' : '启用' }}</el-button>
        </template>
      </el-table-column>
    </el-table>
  
    <!-- 分页 -->
    <div class="pagination">
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
        :current-page.sync="currentPage" :page-sizes="[10, 20, 50, 100]" :page-size="pageSize"
        layout="total, sizes, prev, pager, next" :total="total">
      </el-pagination>
    </div>
  
    <!-- 新增/编辑弹窗 -->
    <el-dialog :close-on-click-modal="false"  :title="dialogType === 'add' ? '新增' : '换卡'" :visible.sync="dialogVisible" width="600px" @close="resetForm">
      <el-form ref="formRef" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="员工" prop="employeeId">
          <el-select filterable  v-model="form.employeeId" clearable placeholder="请选择员工" style="width: 100%">
            <el-option :label="item.nickname" :value="item.id" v-for="item,index in merchantList" :key="index" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'MerchantList',
  data() {
    return {
      // 搜索表单
      searchForm: {
        employeeId: '',
        status: '',
      },
      // 分页
      currentPage: 1,
      pageSize: 10,
      total: 0,
      // 表格数据
      tableData: [],
      loading: false,
      // 弹窗相关
      dialogVisible: false,
      dialogType: 'add', // add 或 edit
      uploadUrl: '', // 上传地址
      form: {
        employeeId: '',
      },
      // 表单校验规则
      rules: {
        employeeId: [{ required: true, message: '请选择员工', trigger: 'blur' }],
      },
      merchantList: []
    }
  },
  created() {
    this.getList();
    this.queryUserList()
  },
  methods: {
    async queryUserList() {
      const { data } = await this.$api.getUserLists({
        page: 1,
        size: 1000,
        condition: {
          nickname: '',
          phone: '',
          status: '',
          type: 2
        }
      })
      this.merchantList = data.result.records
      console.log(data, '商户列表');
    },
    // 获取列表数据
    async getList() {
      this.loading = true
      try {
        const { data } = await this.$api.employeeCardPage({
          page: this.currentPage,
          size: this.pageSize,
          condition: {
            ...this.searchForm
          }
        })
        this.tableData = data.result.records
        this.total = data.result.total
      } catch (error) {
        console.error('获取商家列表失败：', error)
      } finally {
        this.loading = false
      }
    },

    // 搜索
    handleSearch() {
      this.currentPage = 1
      this.getList()
    },

    // 重置搜索
    resetSearch() {
      this.searchForm = {
        areaName: '',
      }
      this.handleSearch()
    },

    // 分页相关
    handleSizeChange(val) {
      this.pageSize = val
      this.getList()
    },

    handleCurrentChange(val) {
      this.currentPage = val
      this.getList()
    },

    // 新增
    handleAdd() {
      this.dialogType = 'add'
      this.dialogVisible = true
    },

    // 编辑
    handleEdit(row) {
      this.dialogType = 'edit'
      this.form = { ...row }
      this.dialogVisible = true
    },

    // 删除
    handleDelete(row) {
      this.$confirm('确认修改状态吗？', '提示', {
        type: 'warning'
      }).then(async () => {
        try {
          await this.$api.employeeCardStatus(row.id, row.status == 1 ? 0 : 1)
          this.$message.success('状态修改成功')
          this.getList()
        } catch (error) {
          console.error('状态修改失败：', error)
        }
      }).catch(() => { })
    },


    // 提交表单
    handleSubmit() {
      this.$refs.formRef.validate(async (valid) => {
        if (valid) {
          try {
            if (this.dialogType === 'add') {
              await this.$api.addEmployeeCard(this.form)
              this.$message.success('新增成功')
            } else {
              const params = {
                ...this.form,
                id: this.form.areaId
              }
              delete params.areaId
              await this.$api.editEmployeeCard(params)
              this.$message.success('换卡成功')
            }
            this.dialogVisible = false
            this.getList()
          } catch (error) {
            console.error(this.dialogType === 'add' ? '新增失败：' : '编辑失败：', error)
          }
        }
      })
    },

    // 重置表单
    resetForm() {
      if (this.$refs.formRef) {
        this.$refs.formRef.resetFields()
      }
      this.form = {
        name: '',
        title: '',
        imageUrl: '',
        address: '',
        phone: '',
        description: ''
      }
    }
  }
}
</script>

<style scoped lang="scss">
.image-uploader {
  .uploaded-image {
    width: 140px;
    height: 140px;
    object-fit: cover;
    border-radius: 4px;
  }

  .upload-placeholder {
    width: 140px;
    height: 140px;
    border: 1px dashed #d9d9d9;
    border-radius: 4px;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    cursor: pointer;
    transition: border-color 0.3s;

    &:hover {
      border-color: #409EFF;
    }

    .el-icon-plus {
      font-size: 28px;
      color: #8c939d;
    }

    .upload-text {
      font-size: 12px;
      color: #8c939d;
      margin-top: 8px;
    }
  }
}

.merchant-list {
  padding: 20px;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 120px;
  height: 120px;
  line-height: 120px;
  text-align: center;
}

.avatar {
  width: 120px;
  height: 120px;
  display: block;
}
</style>